<template>
    <div class="user-list-wrapper">
        <el-card>
            <el-form :inline="true" :model="queryParams" class="mb-2">
                <el-form-item label="会员类型">
                    <el-select v-model="queryParams.user_type" clearable placeholder="全部" size="small"
                        @change="handleQuery">
                        <el-option label="普通用户" value="regular" />
                        <el-option label="试用会员" value="trial_member" />
                        <el-option label="正式会员" value="renewal_member" />
                    </el-select>
                </el-form-item>

                <el-form-item label="注册时间">
                    <el-date-picker v-model="value1" value-format="yyyy-MM-dd" type="daterange" range-separator="-"
                        :start-placeholder="'开始日期'" :end-placeholder="'结束日期'" @change="timeChange">
                    </el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" size="small" icon="el-icon-search" @click="handleQuery">查询</el-button>
                    <el-button type="default" size="small" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
            </el-form>
            <el-table :data="userList" border v-loading="loading" style="width: 100%;">
                <el-table-column prop="user_id" label="id" align="center" />

                <el-table-column prop="user_type" label="会员身份" align="center">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.user_type === 'regular'" type="info">普通</el-tag>
                        <el-tag v-else-if="scope.row.user_type === 'trial_member'" type="success">试用</el-tag>
                        <el-tag v-else-if="scope.row.user_type === 'renewal_member'" type="primary">正式</el-tag>
                        <el-tag v-else-if="scope.row.user_type === 'temporary_member'" type="warning">临时</el-tag>
                        <el-tag v-else type="info">{{ scope.row.user_type }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="subscription_expiry_date" label="过期时间" align="center" />

                <el-table-column prop="balance" label="积分" align="center" />
                <el-table-column prop="current_product_id" label="订阅产品" align="center" show-overflow-tooltip />
                <el-table-column prop="created_at" label="注册时间" align="center" />
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <el-button size="mini" @click="showDetail(scope.row)" type="text">详情</el-button>
                        <el-button size="mini" @click="showRechargeRecords(scope.row)" type="text"
                            style="color: #10b7f5">充值记录</el-button>
                        <el-button size="mini" @click="showConsumeRecords(scope.row)" type="text"
                            style="color: #f59e10">消费记录</el-button>
                        <el-button size="mini" @click="goSongs(scope.row)" type="text"
                            style="color: green">创作列表</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination class="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="queryParams.page" :page-sizes="[10, 20, 50, 100]" :page-size="queryParams.size"
                layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </el-card>

        <!-- 用户详情弹窗，用el-row+el-col每行2列展示字段 -->
        <el-dialog :visible.sync="showDialog" width="1000px" title="用户详情">
            <el-form label-width="160px" size="small">

                <!-- 基础信息 -->
                <el-divider>基础信息</el-divider>
                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="用户ID">
                            <el-input v-model="currentUser.user_id" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="认证类型">
                            <el-input v-model="currentUser.auth_type" disabled />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="谷歌标识">
                            <el-input v-model="currentUser.google_identifier" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="苹果标识">
                            <el-input v-model="currentUser.apple_identifier" disabled />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="用户类型">
                            <el-input v-model="currentUser.user_type" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="国家">
                            <el-input v-model="currentUser.country" disabled />
                        </el-form-item>
                    </el-col>
                </el-row>

                <!-- 账户/订阅 -->
                <el-divider>账户与订阅</el-divider>
                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="积分余额">
                            <el-input v-model="currentUser.balance" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="订阅产品ID">
                            <el-input v-model="currentUser.current_product_id" disabled />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="原始交易ID">
                            <el-input v-model="currentUser.original_transaction_id" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="当前订单ID">
                            <el-input v-model="currentUser.transaction_id" disabled />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="订阅开始时间">
                            <el-input v-model="currentUser.subscription_start_date" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="订阅到期时间">
                            <el-input v-model="currentUser.subscription_expiry_date" disabled />
                        </el-form-item>
                    </el-col>
                </el-row>

                <!-- 注册和活跃信息 -->
                <el-divider>活跃与注册</el-divider>
                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item label="注册时间">
                            <el-input v-model="currentUser.registration_time" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="最后登录时间">
                            <el-input v-model="currentUser.last_login_time" disabled />
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 创建与修改时间 -->
                <el-divider>系统信息</el-divider>
                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="创建时间">
                            <el-input v-model="currentUser.created_at" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="更新时间">
                            <el-input v-model="currentUser.updated_at" disabled />
                        </el-form-item>
                    </el-col>
                </el-row>

            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="showDialog = false">关闭</el-button>
            </span>
        </el-dialog>
        <!-- 充值记录弹窗 -->
        <el-dialog title="充值记录" :visible.sync="showRechargeDialog" width="1000px" @close="closeRechargeDialog">
            <el-table :data="rechargeList" border v-loading="dialogLoading" size="small">
                <el-table-column align="center" prop="transaction_id" label="订单号" />
                <el-table-column align="center" prop="amount" label="充值" width="70" />
                <el-table-column align="center" prop="recharge_time" label="充值时间" />
                <el-table-column align="center" prop="product_id" label="产品ID" width="100" />
                <el-table-column align="center" prop="price" label="订单金额" width="100" />

                <el-table-column align="center" prop="type" label="订单类型" width="100">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.type == '1'" type="success">用户充值</el-tag>
                        <el-tag v-else-if="scope.row.type == '2'" type="info">系统赠送</el-tag>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination class="pagination" @current-change="handleRechargePageChange" :current-page="rechargePage"
                :page-size="rechargePageSize" layout="total, prev, pager, next, jumper" :total="rechargeTotal"
                style="margin: 16px auto 0 auto; text-align:right;" />
            <span slot="footer" class="dialog-footer">
                <el-button @click="showRechargeDialog = false">关闭</el-button>
            </span>
        </el-dialog>

        <!-- 消费记录弹窗 -->
        <el-dialog title="消费记录" :visible.sync="showConsumeDialog" width="1000px" @close="closeConsumeDialog">
            <el-table :data="consumeList" border v-loading="dialogLoading" size="small">
                <el-table-column align="center" prop="amount" label="消费积分" width="110" />
                <el-table-column align="center" prop="before_balance" label="消费前积分" width="110" />
                <el-table-column align="center" prop="after_balance" label="消费后积分" width="110" />
                <el-table-column align="center" prop="created_at" label="消费时间" />
            </el-table>
            <el-pagination class="pagination" @current-change="handleConsumePageChange" :current-page="consumePage"
                :page-size="consumePageSize" layout="total, prev, pager, next, jumper" :total="consumeTotal"
                style="margin: 16px auto 0 auto; text-align:right;" />
            <span slot="footer" class="dialog-footer">
                <el-button @click="showConsumeDialog = false">关闭</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { getUserList, rechargeRecords, consumeRecords } from "@/api/museo";

import axios from 'axios';
export default {
    name: "user-list",
    data() {
        return {
            queryParams: {
                username: '',
                user_type: '',
                momo_balance_min: '',
                invited_count_min: '',
                user_demand: '',
                user_source_channel: '',
                country: '',
                feature_used: '',
                page: 1,
                size: 10,
                dateRange: {
                    start: "",
                    end: "",
                },
            },

            userList: [],
            total: 0,
            loading: false,
            showDialog: false,
            currentUser: {},
            value1: "",
            // 字段key: 显示名，按 transir_users 字段全列
            userFields: {
                user_id: "用户ID",
                auth_type: "认证类型",
                google_identifier: "谷歌标识",     // 或你想自定义展示“微信标识”
                apple_identifier: "苹果标识",
                balance: "积分余额",
                registration_time: "注册时间",
                last_login_time: "最后登录时间",
                user_type: "用户类型",
                current_product_id: "订阅产品ID",
                original_transaction_id: "原始订单ID",
                transaction_id: "当前订单ID",
                subscription_start_date: "订阅开始时间",
                subscription_expiry_date: "订阅到期时间",
                invitation_code: "邀请码",
                invited_count: "邀请人数",
                invite_reward_pending_days: "邀请奖励待兑换天数",
                invite_reward_redeemed_days: "已兑换天数",
                post_vip_pending_days: "会员过期后暂存生效天数",
                invited_by: "邀请人ID",
                invitation_time: "被邀请时间",
                last_active_time: "最后活跃时间",
                country: "国家",
                feature_used: "功能是否用过",
                created_at: "创建时间",
                updated_at: "更新时间"
            },

            showRechargeDialog: false,
            showConsumeDialog: false,
            rechargeList: [],
            rechargePage: 1,
            rechargePageSize: 10,
            rechargeTotal: 0,
            consumeList: [],
            consumePage: 1,
            consumePageSize: 10,
            consumeTotal: 0,
            dialogLoading: false,
            currentUserId: null, // 记录当前弹窗的用户id
            demandOptions: ['追剧党', '追星党', '小说党', '漫画党', '留学生', '外贸员', '爬梯党'],
            sourceChannelOptions: ['裂变', '自然流', '小红书', '微博'],
            countryOptions: [],
            featureUsedList: [
                {
                    value: 0,
                    label: '否'
                },
                {
                    value: 1,
                    label: '是'
                },
            ],

        };
    },
    methods: {
        parseJsonSafe(val) {
            if (!val) return [];
            try {
                return Array.isArray(val) ? val : JSON.parse(val);
            } catch {
                return [];
            }
        },
        handleQuery() {
            this.queryParams.page = 1;
            this.getUsers();
        },
         
        async getUsers() {
            this.loading = true;
            try {
                // 发送 POST 请求
                let   res = await getUserList(this.queryParams);
                console.log(res)
                if (res.code === 1) {
                    this.userList = res.data || [];
                    this.total = res.total || 0;
                } else {
                    this.$message.error(res.msg || "获取用户数据失败");
                }
            } catch (e) {
                this.$message.error('获取用户数据失败');
            }
            this.loading = false;
        },
        timeChange() {
            this.queryParams.dateRange.start = this.value1[0];
            this.queryParams.dateRange.end = this.value1[1];
            this.getUsers();
        },
        handleCurrentChange(page) {
            this.queryParams.page = page;
            this.getUsers();
        },
        handleSizeChange(size) {
            this.queryParams.size = size;
            this.queryParams.page = 1;
            this.getUsers();
        },
        resetQuery() {
            this.queryParams.username = '';
            this.queryParams.momo_balance_min = '';
            this.queryParams.invited_count_min = '';
            this.queryParams.user_type = '';
            this.queryParams.user_demand = '';
            this.queryParams.user_source_channel = '';
            this.queryParams.country = '';
            this.queryParams.feature_used = '';

            this.value1 = '';
            this.queryParams.page = 1;
            this.queryParams.dateRange.start = null;
            this.queryParams.dateRange.end = null;
            this.getUsers();
        },
        showDetail(row) {
            this.currentUser = Object.assign({}, row);
            this.showDialog = true;
        },
        goSongs(row) {
            this.$router.push({
                path: '/Museo/songs',
                query: {
                    user_id: row.user_id
                }
            });
        },
        // 点击操作列的 充值记录按钮
        showRechargeRecords(row) {
            this.currentUserId = row.user_id;
            this.rechargePage = 1;
            this.getRechargeRecords();
            this.showRechargeDialog = true;
        },
        // 点击分页
        handleRechargePageChange(page) {
            this.rechargePage = page;
            this.getRechargeRecords();
        },
        async getRechargeRecords() {
            this.dialogLoading = true;
            try {
                let res = await rechargeRecords({
                    user_id: this.currentUserId,
                    page: this.rechargePage,
                    pageSize: this.rechargePageSize
                }) 
                if (res.code === 0) {
                    const { list, total } = res.data;
                    this.rechargeList = list;
                    this.rechargeTotal = total;
                } else {
                    this.$message.error(res.msg || "获取充值记录失败");
                }
            } catch (e) {
                this.$message.error("网络异常！");
            }
            this.dialogLoading = false;
        },
        closeRechargeDialog() {
            this.showRechargeDialog = false;
            this.rechargeList = [];
            this.currentUserId = null;
            this.rechargePage = 1;
        },

        // 消费记录
        showConsumeRecords(row) {
            this.currentUserId = row.user_id;
            this.consumePage = 1;
            this.getConsumeRecords();
            this.showConsumeDialog = true;
        },
        handleConsumePageChange(page) {
            this.consumePage = page;
            this.getConsumeRecords();
        },
        async getConsumeRecords() {
            this.dialogLoading = true;
            try {
                let res = await consumeRecords({
                    user_id: this.currentUserId,
                    page: this.consumePage,
                    pageSize: this.consumePageSize
                })  
                if (res.code === 0) {
                    const { list, total } = res.data;
                    this.consumeList = list;
                    this.consumeTotal = total;
                } else {
                    this.$message.error(res.msg || "获取消费记录失败");
                }
            } catch (e) {
                this.$message.error("网络异常！");
            }
            this.dialogLoading = false;
        },
        closeConsumeDialog() {
            this.showConsumeDialog = false;
            this.consumeList = [];
            this.currentUserId = null;
            this.consumePage = 1;
        },
        // 消费明细解析
        parseConsumeDetail(detailJson) {
            if (!detailJson) return [];
            try {
                return typeof detailJson === 'string' ? JSON.parse(detailJson) : detailJson;
            } catch { return []; }
        },
    },
    created() {
        this.getUsers();
    }
};
</script>

<style scoped>
.user-list-wrapper {
    padding: 18px 8px 32px 8px;
    background: #f7f7f7;
    min-height: 90vh;
}

.mb-2 {
    margin-bottom: 18px;
}

.pagination {
    margin: 18px auto 0 auto;
    text-align: right;
}

::v-deep .el-input.is-disabled .el-input__inner {
    color: #333;
}
</style>
